#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    downloadImg();
}

void MainWindow::downloadImg()
{
    //循环拼接
    QString baseUrl = "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1592571342481&di=7e238b88ac9dcd647c23812ae43b9b50&imgtype=0&src=http%3A%2F%2Fa0.att.hudong.com%2F64%2F76%2F20300001349415131407760417677.jpg";
    //构造请求
    QNetworkRequest request;
    request.setUrl(QUrl(baseUrl));
    QNetworkAccessManager *manager = new QNetworkAccessManager();
    // 发送请求
    connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyFinished(QNetworkReply*)));

    QUrl url;
    url = QUrl(baseUrl);

    request.setUrl(url);

    manager->get(request);
}

void MainWindow::replyFinished(QNetworkReply* reply){

    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray bytes = reply->readAll();

        QString desktop_path = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation) + "/test.png";

        qDebug() << desktop_path;

        QFile file(desktop_path);
        if (file.open(QIODevice::Append))
        {
            file.write(bytes);
        }
        file.close();
    }
    else
    {
        qDebug() << "Error\n";
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}
